package cn.net.isir.core;

import cn.net.isir.entity.Permission;
import cn.net.isir.entity.Role;
import cn.net.isir.entity.User;
import cn.net.isir.service.RolePermissionService;
import cn.net.isir.service.UserRoleService;
import cn.net.isir.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author liuxubo
 * @filename ShiroAuthorizingRealm.java
 * @package cn.net.isir.core
 * @email lxb@isir.net.cn
 * @date 2018/11/09
 * @comment
 * @since 1.8
 */
public class ShiroAuthorizingRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;
    @Resource
    private UserRoleService userRoleService;
    @Resource
    private RolePermissionService rolePermissionService;

    public ShiroAuthorizingRealm() {
        super();
    }

    /**
     * Retrieves authentication data from an implementation-specific datasource (RDBMS, LDAP, etc) for the given
     * authentication token.
     * <p/>
     * For most datasources, this means just 'pulling' authentication data for an associated subject/user and nothing
     * more and letting Shiro do the rest.  But in some systems, this method could actually perform EIS specific
     * log-in logic in addition to just retrieving data - it is up to the Realm implementation.
     * <p/>
     * A {@code null} return value means that no account could be associated with the specified token.
     *
     * @param token the authentication token containing the user's principal and credentials.
     * @return an {@link AuthenticationInfo} object containing account data resulting from the
     * authentication ONLY if the lookup is successful (i.e. account exists and is valid, etc.)
     * @throws AuthenticationException if there is an error acquiring data or performing
     *                                 realm-specific authentication logic for the specified <tt>token</tt>
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();
        // 验证用户是否可以登录
        User user = new User();
        user.setUsername(username);
        user = userService.selectOne(user);
        if (user == null) {
            throw new UnknownAccountException("用户不存在");
        }
        if ("-1".equals(user.getStatus())) {
            throw new LockedAccountException("账户已锁定");
        }
        if ("0".equals(user.getStatus())) {
            throw new DisabledAccountException("账户已失效");
        }
        // 设置session
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute("ShiroAuthorizingRealm-current-user", user);
        // 以下信息从数据库中获取
        // 1 principal : 认证的实体信息，可以是username,也可以是数据表对应的实体对象。
        // Object principal = username;
        // 3 realmName : 当前realm 对象的name ， 调用父类的 getName() 方法即可
        // String realmName = getName();
        // 4.盐值
        // ByteSource credentialsSalt = ByteSource.Util.bytes(username);
        // 这个是不加盐的 new SimpleAuthenticationInfo(principal, credentials, realmName);


        //principal - the 'primary' principal associated with the specified realm.
        //credentials - the credentials that verify the given principal.
        //realmName - the realm from where the principal and credentials were acquired.
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(upToken.getUsername(), user.getPassword(),getName());
        //设置盐值
        info.setCredentialsSalt(ByteSource.Util.bytes(upToken.getUsername()));
        return info;
    }

    /**
     * Retrieves the AuthorizationInfo for the given principals from the underlying data store.  When returning
     * an instance from this method, you might want to consider using an instance of
     * {@link SimpleAuthorizationInfo SimpleAuthorizationInfo}, as it is suitable in most cases.
     *
     * @param principals the primary identifying principals of the AuthorizationInfo that should be retrieved.
     * @return the AuthorizationInfo associated with this principals.
     * @see SimpleAuthorizationInfo
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String) getAvailablePrincipal(principals);
        SimpleAuthorizationInfo authorizationInfo = null;
        if (username != null) {
            User user = new User();
            user.setUsername(username);
            user = userService.selectOne(user);
            List<Permission> permissionList = rolePermissionService.selectPermissionListByUserId(String.valueOf(user.getId()));
            authorizationInfo = new SimpleAuthorizationInfo();
            if (permissionList != null && permissionList.size() > 0) {
                for (Permission permission : permissionList) {
                    authorizationInfo.addStringPermission(permission.getPermissionValue());
                }
            }
            List<Role> roleList = userRoleService.selectRoleListByUserId(String.valueOf(user.getId()));
            if (roleList != null && roleList.size() > 0) {
                Set<String> roleSet = new HashSet<>();
                for (Role role : roleList) {
                    roleSet.add(role.getRoleValue());
                }
                authorizationInfo.setRoles(roleSet);
            }
        }
        return authorizationInfo;
    }

    /**
     * Clears out the AuthorizationInfo cache entry for the specified account.
     * <p/>
     * This method is provided as a convenience to subclasses so they can invalidate a cache entry when they
     * change an account's authorization data (add/remove roles or permissions) during runtime.  Because an account's
     * AuthorizationInfo can be cached, there needs to be a way to invalidate the cache for only that account so that
     * subsequent authorization operations don't used the (old) cached value if account data changes.
     * <p/>
     * After this method is called, the next authorization check for that same account will result in a call to
     * {@link #getAuthorizationInfo(PrincipalCollection) getAuthorizationInfo}, and the
     * resulting return value will be cached before being returned so it can be reused for later authorization checks.
     * <p/>
     * If you wish to clear out all associated cached data (and not just authorization data), use the
     * {@link #clearCache(PrincipalCollection)} method instead (which will in turn call this
     * method by default).
     *
     * @param principals the principals of the account for which to clear the cached AuthorizationInfo.
     */
    @Override
    public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
        super.clearCachedAuthorizationInfo(principals);
    }
}
